package work;

import java.util.*;

/**
 * 子域名访问计数
 * 时间复杂度：O(length of cpdomains * length of cpdomains[i])
 * 思路：HashMap
 * 注意点：map不能边遍历，边修改
 */
public class SubdomainVisits {

    public List<String> subdomainVisits(String[] cpdomains) {
        Map<String, Integer> map = new HashMap();
        for (String domain: cpdomains) {
            String[] cpinfo = domain.split("\\s+");
            String[] frags = cpinfo[1].split("\\.");//正则表达式.是特殊字符，所以需要转义。注意点
            int count = Integer.valueOf(cpinfo[0]);
            String cur = "";
            for (int i = frags.length - 1; i >= 0; --i) {
                cur = frags[i] + (i < frags.length - 1 ? "." : "") + cur;
                map.put(cur, map.getOrDefault(cur, 0) + count);
            }
        }

        List<String> ans = new ArrayList();
        for (String dom: map.keySet())
            ans.add("" + map.get(dom) + " " + dom);
        return ans;
    }

    public static void main(String[] args) {
        String[] cpdomains = {"2777 nak.mkw.co","654 yaw.lmm.ca"};
        List<String> ans = new SubdomainVisits().subdomainVisits(cpdomains);
        System.out.println(ans.toString());


    }


}
